package 死锁;

public class 必然死锁 {

//    两个资源
    private static Object resources1 = new Object();
    private static Object resources2 = new Object();

    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
//                对资源上锁
                synchronized (resources1) {
                    System.out.println("线程1成功占用资源1，请求资源2");

//                    确保形成必然死锁，保证线程1抢不到资源2
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (resources2) {
                        System.out.println("线程1成功占有资源2");
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resources2) {
                    System.out.println("线程2成功占用资源2，请求资源1");

//                    确保形成必然死锁，保证线程2抢不到资源1
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (resources1) {
                        System.out.println("线程2成功占有资源1");
                    }
                }
            }
        }).start();

    }
}
